from django.db import models
from django.utils import timezone
from user_management.models import CustomUser


class UserSession(models.Model):
    """用户会话模型"""
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='用户')
    session_key = models.CharField(max_length=255, unique=True, verbose_name='会话密钥')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(verbose_name='用户代理')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    last_activity = models.DateTimeField(default=timezone.now, verbose_name='最后活动时间')
    expires_at = models.DateTimeField(verbose_name='过期时间')

    class Meta:
        db_table = 'user_sessions'
        verbose_name = '用户会话'
        verbose_name_plural = '用户会话'
        ordering = ['-last_activity']

    def __str__(self):
        return f"{self.user.username} - {self.session_key[:10]}..."


class UserLoginAttempt(models.Model):
    """用户登录尝试模型"""
    username = models.CharField(max_length=150, verbose_name='用户名')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(verbose_name='用户代理')
    is_success = models.BooleanField(verbose_name='是否成功')
    failure_reason = models.CharField(max_length=255, blank=True, verbose_name='失败原因')
    attempted_at = models.DateTimeField(default=timezone.now, verbose_name='尝试时间')

    class Meta:
        db_table = 'user_login_attempts'
        verbose_name = '登录尝试'
        verbose_name_plural = '登录尝试'
        ordering = ['-attempted_at']

    def __str__(self):
        status = '成功' if self.is_success else '失败'
        return f"{self.username} - {status} - {self.attempted_at}"
